import React, { useEffect, useState } from 'react';
import { View, Text, Button, TouchableOpacity, StyleSheet, FlatList, Modal } from 'react-native';
import { Divider } from '@rneui/base';
import { CommonStyle } from '../common/commonStyle.ts';
import Tools from '../utils/Tools.ts';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import EmptyCom from './Empty.tsx';

export interface TreeNode {
  name: string;
  id: number;
  levels?: number;
  children?: TreeNode[];
}

interface CascaderProps {
  title?: string;
  show: boolean;
  data: TreeNode[];
  selectedIds?: number[];
  onChange?: (selectedValues: TreeNode[], ids: number[]) => void;
  onClose: () => void;
  onConfirm: (selectedValues: TreeNode[], ids: number[]) => void;
  closeOnClickOverlay?: boolean;
}

const CascadingPicker: React.FC<CascaderProps> = ({ data, closeOnClickOverlay, title, onChange, selectedIds, show, onClose, onConfirm }) => {
  const [isModalVisible, setModalVisible] = useState(false);
  const [selected, setSelected] = useState<TreeNode[]>([]);

  useEffect(() => {
    if (data && selectedIds && selected.length === 0) {
      selectedIds.forEach((item) => {
        setSelected((prevState) => prevState.concat(Tools.findTreeNodeById(data, item)));
      });
    }
  }, []);

  useEffect(() => {
    if (selectedIds && selectedIds.length > 0 && selected.length === 0) {
      selectedIds.forEach((item) => {
        setSelected((prevState) => prevState.concat(Tools.findTreeNodeById(data, item)));
      });
    }
    setModalVisible(show);
  }, [show]);

  useEffect(() => {
    if (selectedIds?.length === 0) {
      setSelected([]);
    }
  }, [selectedIds]);

  useEffect(() => {
    onChange &&
      onChange(
        selected.map((c) => {
          return { ...c, children: [] };
        }),
        selected.map((c) => c.id),
      );
  }, [selected]);

  const toggleModal = () => {
    setModalVisible(!isModalVisible);
    onClose();
  };

  const handleSelect = (item: TreeNode) => {
    let lock = false;
    selected.forEach((item) => {
      if (!item.children) lock = true;
    });
    if (!lock) {
      setSelected((prevState) => prevState.concat(item));
    } else {
      // 替换最后一位
      setSelected((prevArray) => {
        return prevArray.map((prev, index) => (index === prevArray.length - 1 ? item : prev));
      });
    }
    if (!item.children) {
      toggleModal();
    }
  };

  const handleTabClick = (item: TreeNode, index: number) => {
    setSelected((prevArray) => prevArray.slice(0, index));
  };

  const renderTab = () => (
    <View style={styles.tabContainer}>
      {selected.length > 0 ? (
        selected.map((item, index) => {
          return (
            <TouchableOpacity key={index} onPress={() => handleTabClick(item, index)}>
              <Text style={styles.tabText}>{item.name || '请选择'}</Text>
            </TouchableOpacity>
          );
        })
      ) : (
        <TouchableOpacity onPress={() => {}}>
          <Text style={styles.tabText}>{'请选择'}</Text>
        </TouchableOpacity>
      )}
    </View>
  );

  const renderList = (data: TreeNode[]) => (
    <FlatList
      data={selected.length === 0 ? data : selected[selected.length - 1].children ? selected[selected.length - 1].children : selected[selected.length - 2].children}
      keyExtractor={(item, index) => index.toString()}
      renderItem={({ item }) => (
        <TouchableOpacity onPress={() => handleSelect(item)}>
          <Text style={selected.find((c) => c.id === item.id) ? styles.activeTabText : styles.listItem}>{item.name}</Text>
        </TouchableOpacity>
      )}
      ListEmptyComponent={
        <View style={{ height: 300 }}>
          <EmptyCom text={'已经选完了'} />
        </View>
      }
    />
  );

  const handleCascaderConfirm = () => {
    onConfirm(
      selected.map((c) => {
        return { ...c, children: [] };
      }),
      selected.map((c) => c.id),
    );
  };

  return (
    <>
      <Modal visible={isModalVisible} transparent animationType="fade">
        <View style={styles.container}>
          <Touchable
            style={styles.touchArea}
            onPress={() => {
              closeOnClickOverlay ? onClose() : undefined;
            }}
          >
            <View></View>
          </Touchable>
          <View style={styles.pickerContainer}>
            {/* 标题和按钮 */}
            <View style={styles.header}>
              <TouchableOpacity onPress={onClose}>
                <Text style={(styles.button, { color: '#969799' })}>取消</Text>
              </TouchableOpacity>
              <Text style={styles.title}>{title}</Text>
              <TouchableOpacity onPress={handleCascaderConfirm}>
                <Text style={styles.button}>确认</Text>
              </TouchableOpacity>
            </View>

            <View style={styles.pickerContent}>
              {renderTab()}
              {renderList(data)}
            </View>
          </View>
        </View>
      </Modal>
    </>
  );
};

export default CascadingPicker;

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'flex-end', backgroundColor: 'rgba(0,0,0,0.2)' },
  touchArea: { flex: 1, backgroundColor: 'rgba(0,0,0,0.2)' },
  pickerContainer: { backgroundColor: '#fff', borderTopLeftRadius: 20, borderTopRightRadius: 20, paddingBottom: 20 },
  header: { flexDirection: 'row', justifyContent: 'space-between', padding: 15, borderBottomWidth: 1, borderBottomColor: '#ddd' },
  title: { fontSize: 16, fontWeight: 'bold' },
  button: { fontSize: 14, color: '#333333' },
  pickerContent: { position: 'relative', height: 350, justifyContent: 'center', paddingHorizontal: 16 },

  tabContainer: { flexDirection: 'row', marginVertical: 10 },
  tabText: { marginRight: 10, fontSize: 14, color: CommonStyle.mainColor },
  activeTabText: { color: CommonStyle.mainColor, paddingVertical: 10, fontSize: 13 },
  listItem: { paddingVertical: 10, fontSize: 14, color: '#333' },
});
